package org.madmatrix.galarm;

import org.madmatrix.glib.log.ILogger;
import org.madmatrix.glib.log.LoggerFactory;

import android.app.Activity;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.Vibrator;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.TextView;

import com.google.gson.Gson;

/**
 * 闹铃到期后展示的界面
 * 
 * @author madmatrix
 */
public class AlarmExpireActivity extends Activity {

	private static ILogger logger = LoggerFactory.getLogger(AlarmExpireActivity.class);
	private Gson mGson = new Gson();

	private TextView tvTime;
	private TextView tvMemo;
	private Vibrator mVibrator;
	private PowerManager.WakeLock mWakeLock;
	private MediaPlayer mMdeiaPlayer;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_alarm_expire);

		tvTime = (TextView) findViewById(R.id.time);
		tvMemo = (TextView) findViewById(R.id.memo);

		// 点击对话框销毁自身
		findViewById(R.id.dialog).setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

		String alarmConf = getIntent().getStringExtra("alarm");
		if (!TextUtils.isEmpty(alarmConf)) {
			// 激活屏幕
			unlockScreen();
			lightScreen();

			Alarm alarm = mGson.fromJson(alarmConf, Alarm.class);
			// 使用本地数据，以保证读取正确的闹钟状态
			alarm = GAlarmManager.getAlarm(this, alarm.id);
			logger.d("alarm expires, show the ExpireActivity, alarm=" + alarm);

			if (alarm.isEnabled) {
				// 设置到期时间和备注信息
				tvTime.setText(GAlarmManager.getTriggerTime(alarm));
				if (!TextUtils.isEmpty(alarm.memo)) {
					tvMemo.setText(alarm.memo);
				}

				// 让时间文本闪烁
				Animation alphaAnimation = new AlphaAnimation(1, 0);
				alphaAnimation.setDuration(600);
				alphaAnimation.setInterpolator(new LinearInterpolator());
				alphaAnimation.setRepeatCount(Animation.INFINITE);
				alphaAnimation.setRepeatMode(Animation.REVERSE);
				tvTime.startAnimation(alphaAnimation);
				
				// 震动
				if (alarm.isVibrate) {
					mVibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
					long[] pattern = new long[] { 1000, 500 };
					mVibrator.vibrate(pattern, 0);
				}
				
				// 播放铃声
				mMdeiaPlayer = MediaPlayer.create(this, Uri.parse(alarm.alarmRingUri));
				if (null != mMdeiaPlayer) {
					mMdeiaPlayer.setLooping(true);
					mMdeiaPlayer.start();
				}

				// 设置下一次响铃
				if (alarm.isRepeat) {
					GAlarmManager.resetAlarm(this, alarm, true);
				} else { // 仅响铃一次，则响铃过后就禁用
					GAlarmManager.enableAlarm(this, alarm, false);
				}

				// 发送到期广播
				Intent broadcast = new Intent(Constants.ACTION_ALARM_EXPIRES);
				broadcast.putExtra("alarm", alarm.toJson());
				LocalBroadcastManager.getInstance(this).sendBroadcast(broadcast);
			} else { // 如果该闹钟已经被禁用，则启动主界面
				startActivity(new Intent(this, MainActivity.class));
			}
		} else {
			logger.e("'alarm' is required!");
			finish();
		}
	}

	@Override
	protected void onPause() {
		super.onPause();

		if (null != mVibrator) {
			mVibrator.cancel();
		}
		
		if (null != mMdeiaPlayer) {
			mMdeiaPlayer.stop();
		}

		// 释放屏幕常亮锁
		if (null != mWakeLock && mWakeLock.isHeld()) {
			mWakeLock.release();
		}
	}

	/**
	 * 解锁屏幕
	 */
	private void unlockScreen() {
		KeyguardManager keyguardMgr = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
		KeyguardLock keyguardLock = keyguardMgr.newKeyguardLock("unlock");
		keyguardLock.disableKeyguard();
	}

	/**
	 * 点亮屏幕
	 */
	private void lightScreen() {
		PowerManager powerMgr = (PowerManager) getSystemService(Context.POWER_SERVICE);
		mWakeLock = powerMgr.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "[lightScreen]");
		mWakeLock.acquire();
	}
}
